from sqlalchemy import select, asc, delete
from sqlalchemy.ext.asyncio import AsyncSession

from core.decorators.database_decorator import with_async_session
from core.utils.paginator import Paginator
from src.modules.knowbase.repository.entity.kb_file import KnowledgeBase
from src.modules.knowbase.schemas.model_schema import KnowBaseResponse


class KBDao:
    @staticmethod
    @with_async_session()
    async def get_kb_list(user_id: str = None, keyword: str = None,
                          page: int = 1, page_size: int = 10,
                          session:AsyncSession = None):
        query = select(KnowledgeBase)
        if user_id:
            query = query.where(KnowledgeBase.create_user_id == user_id)
        if keyword:
            query = query.where(KnowledgeBase.know_base_name.ilike(f"%{keyword}%"))
        query = query.order_by(asc(KnowledgeBase.uid))
        paginator = Paginator(session=session,
                              model=KnowledgeBase,
                              response_model=KnowBaseResponse,
                              base_query=query)
        return await paginator.paginate(page=page, page_size=page_size)

    @staticmethod
    @with_async_session(auto_commit=False)
    async def create_kb(kb_name: str, user_id: str = None, session: AsyncSession = None):
        kb = KnowledgeBase(know_base_name=kb_name,
                           create_user_id=user_id)
        session.add(kb)
        await session.commit()
        await session.refresh(kb)
        if kb.uid is None:
            return None
        return kb
    
    @staticmethod
    @with_async_session()
    async def delete_by_kb_id(kb_id:str,session:AsyncSession = None):
        delete_sql = delete(KnowledgeBase).where(KnowledgeBase.know_base_id == kb_id)
        result = await session.execute(delete_sql)
        return result.rowcount>0
